package com.wendyxie.sproutup.view.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.wendyxie.sproutup.R
import com.wendyxie.sproutup.databinding.ItemUserScoreRecordBinding
import com.wendyxie.sproutup.entity.UserScoreRecordEntity
import com.wendyxie.sproutup.enum.ScoreStatusEnum
import java.time.format.DateTimeFormatter

class UserScoreRecordAdapter : RecyclerView.Adapter<UserScoreRecordAdapter.ItemAdapterHolder>() {

    private val scores = mutableListOf<UserScoreRecordEntity>()

    class ItemAdapterHolder(val binding: ItemUserScoreRecordBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(score: UserScoreRecordEntity) {
            binding.tvScoreValue.text = score.score.toString() + "g(共" + score.totalScoreEnd.toString() + "g)"
            binding.tvScoreTitle.text = score.scoreTitle
            binding.tvDate.text = score.scoreTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
            if (score.scoreStatus == ScoreStatusEnum.CREATE) {
                binding.tvStatus.visibility = ViewGroup.VISIBLE
                binding.tvStatus.text = "等待收集"
            } else {
                binding.tvStatus.visibility = ViewGroup.GONE
            }

            // 如果时间是今天，则修改背景色
            if (score.scoreTime.toLocalDate().toString() == java.time.LocalDate.now().toString()) {
                binding.llContainer.setBackgroundColor(binding.tvDate.context.getColor(R.color.colorPrimaryLight))
            }
        }
    }

    fun addItems(newItems: List<UserScoreRecordEntity>) {
        if (newItems.isEmpty()) {
            return
        }
        val startIndex = scores.size
        Log.d("UserScoreRecordAdapter", "addItems: startIndex: $startIndex")
        scores.addAll(newItems)
        notifyItemRangeInserted(startIndex, newItems.size)
    }

    fun clearItems() {
        scores.clear()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemAdapterHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding = ItemUserScoreRecordBinding.inflate(layoutInflater, parent, false)
        return ItemAdapterHolder(binding)
    }

    override fun onBindViewHolder(holder: ItemAdapterHolder, position: Int) {
        holder.bind(scores[position])
    }

    override fun getItemCount(): Int = scores.size


}
